package com.github.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import java.security.MessageDigest;
import java.util.UUID;

@Component
public class Utils {
    private final static ObjectMapper objectMapper = new ObjectMapper();

    public static String encrypt() {
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < 32; i++) {
            str.append((char) ("wTRZr:[dDBsHYDB88SE]{yGHvui\\NjeY".charAt(i) - 3));
        }
        return str.toString();
    }

    // 获取Token
    public static String getToken() {
        try {
            String uuid = UUID.randomUUID().toString().replace("-", "");
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(uuid.getBytes());
            byte[] digest = md5.digest();
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (Exception e) {
            return null;
        }
    }

    public static JsonNode toJsonNode(String str) {
        try {
            return objectMapper.readTree(str);
        } catch (Exception e) {
            return null;
        }
    }

    public static String getRandomString(int i) {
        String str = "0123456789";
        StringBuilder sb = new StringBuilder();
        for (int j = 0; j < i; j++) {
            int number = (int) (Math.random() * str.length());
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }
}
